package com.ly.user_system.common;

import com.ly.user_system.utils.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 是否支持advice功能
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除已经包装过的响应和不需要包装的响应
        return !returnType.getParameterType().isAssignableFrom(R.class)&& !returnType.hasMethodAnnotation(NoWrapResponse.class);
    }

    /**
     * 处理响应
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 处理String类型返回值
        if (body instanceof String) {
            return body;
        }

        // 处理void返回类型
        if (returnType.getGenericParameterType().equals(void.class)) {
            return R.ok();
        }

        // 已经包装过的响应直接返回
        if (body instanceof R) {
            return body;
        }

        // 其他情况统一包装
        return R.ok(body);
    }
}
